<?php
// app/service/RabbitMQProducer.php
namespace app\wsns\service;



use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\facade\Log;


class RabbitMQProducer
{
    protected $connection;
    protected $channel;
    protected $config;

    public function __construct()
    {
//        $this->config = config('amqp');
//        $this->connection = new AMQPStreamConnection(
//            $this->config['host'],
//            $this->config['port'],
//            $this->config['user'],
//            $this->config['password'],
//            $this->config['vhost']
//        );
        try {
            $this->connection = new AMQPStreamConnection(
                '121.40.150.13',
                5672,
                'admin',
                '8bec07d4',
                '/'
            );
        }catch (\Exception $e){
            LOG::INFO( '异常了');
            LOG::INFO( json_encode($e));
            LOG::INFO( $e);
        }

        $this->channel = $this->connection->channel();
    }

    public function send($queueName, $message)
    {
        // 声明队列
        $this->channel->queue_declare($queueName, false, true, false, false);

        $msg = new AMQPMessage($message, [
            'content_type' => 'text/plain',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT // 持久化消息
        ]);

        $this->channel->basic_publish($msg, '', $queueName);

        echo "消息已发送: $message\n";
    }

    public function send2($queueName, $message)
    {
//        try{
//            return "ok";
//        }catch (Exception $e){
//            return $e;
//        }
        //$this->channel->queue_declare($queueName, false, true, false, false);

        $msg = new AMQPMessage($message, [
            'content_type' => 'text/plain',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT // 持久化消息
        ]);

        $this->channel->basic_publish($msg, '', $queueName);

        echo "消息已发送: $message\n";
    }

    public function close()
    {
        $this->channel->close();
        $this->connection->close();
    }
}